package com.itheima.Controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.expr.NewExpr;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * reggie-com.itheima.Controller
 * Administrator
 * 2023-03-09
 * 16:00
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;


    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    public R saveDish(@RequestBody DishDto dishDto) {
        boolean save = dishService.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();

        //判断是否选择了口味
        if (flavors != null && flavors.size() > 0) {
            //保存菜品的口味数据 需要注意：DishFlavor中dishId是没有数据的，
            // 所以需要手动设置
            Long id = dishDto.getId();//获取菜id
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
                dishFlavorService.save(flavor);
            }

        }
        if (save) {

            //删除redis
            Long categoryId = dishDto.getCategoryId();
            redisTemplate.delete("dish_"+categoryId);
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(!StringUtils.isEmpty(name), Dish::getName, name);
        Page<Dish> page1 = dishService.page(dishPage, lqw);
        long total = page1.getTotal();
        if (page1 != null) {
            ArrayList<DishDto> dishDtos = new ArrayList<>();
            List<Dish> records = page1.getRecords();
            for (Dish record : records) {
                Long categoryId = record.getCategoryId();
                Category one = categoryService.getById(categoryId);
                if (one != null) {
                    String categoryName = one.getName();
                    DishDto dishDto = new DishDto();
                    dishDto.setCategoryName(categoryName);
                    BeanUtils.copyProperties(record, dishDto);
                    dishDtos.add(dishDto);
                }
            }
            dishDtoPage.setRecords(dishDtos);
            dishDtoPage.setTotal(total);
            return R.success(dishDtoPage);
        }

        return R.error("查询失败");
    }

    @GetMapping("/{id}")
    //注意id的数据类型
    public R selectById(@PathVariable Long id) {
        log.info("修改", id);
        Dish dish = dishService.getById(id);
        if (dish != null) {
            DishDto dishDto = new DishDto();
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String name = category.getName();
            dishDto.setCategoryName(name);
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId, id);
            List<DishFlavor> list = dishFlavorService.list(lqw);
            BeanUtils.copyProperties(dish, dishDto);
            dishDto.setFlavors(list);
            return R.success(dishDto);
        }
        return R.error("查找失败");
    }

    @CacheEvict(value = "dish_cache",key = "'dish_'+#dishDto.getCategoryId()")
    @PutMapping
    public R updateDish(@RequestBody DishDto dishDto) {
        //更新dish表基本信息
        boolean b = dishService.updateById(dishDto);
        if (b) {
            //清理当前菜品对应口味数据---dish_flavor表的delete操作
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            Long id = dishDto.getId();
            lqw.eq(DishFlavor::getDishId, id);
            dishFlavorService.remove(lqw);

            //添加当前提交过来的口味数据---dish_flavor表的insert操作
            List<DishFlavor> flavors = dishDto.getFlavors();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            dishFlavorService.saveBatch(flavors);
            return R.success("修改菜品成功");
        }
       return R.error("修改失败");
    }

    @DeleteMapping
    public  R deleteDish(@RequestParam("ids") List<Long> ids){
        //LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //lqw.in(Dish::getId,ids);
        //boolean remove = dishService.remove(lqw);
        boolean remove = dishService.removeByIds(ids);
        if (remove){
            for (Long id : ids) {
                LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper<>();
                lqw1.eq(DishFlavor::getDishId,id);
                boolean remove1 = dishFlavorService.remove(lqw1);
            }
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    @PostMapping("/status/{status}")
    public R status(@PathVariable Integer status,@RequestParam List<Long> ids){
        int count=0;
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            boolean b = dishService.updateById(dish);
            count++;
        }
        if (count==ids.size()){
            return R.success("操作成功");
        }
        return R.error("操作失败");
    }



    //根据分类id查询该分类下的所有菜品集合
    @GetMapping("/list")

    //redis优化
 //   * condition：条件，满足条件时才缓存数据
 //* unless：满足条件则不缓存
    @Cacheable(value = "dish_cache",key = "'dish_'+#categoryId",unless = "#result==null")
    public R selectDishById(Long categoryId){
        log.info("categoryId的值{}"+categoryId);

        //redis优化：方法一
        //ArrayList<DishDto> dishdtos = (ArrayList<DishDto>) redisTemplate.opsForValue().get("dish_" + categoryId);
        //if (dishdtos!=null&&dishdtos.size()!=0){
        //    return  R.success(dishdtos);
        //}

        ArrayList<DishDto> dishDtos = new ArrayList<>();
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId,categoryId);
        List<Dish> list = dishService.list(lqw);
        if (list!=null&&list.size()!=0){
            for (Dish dish : list) {
                DishDto dishDto = new DishDto();
                LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper<>();
                lqw1.eq(DishFlavor::getDishId,dish.getId());
                List<DishFlavor> list1 = dishFlavorService.list(lqw1);
                BeanUtils.copyProperties(dish,dishDto);
                dishDto.setFlavors(list1);
                dishDtos.add(dishDto);
            }

            //方法一：如果redis不存在数据 将数据库查询到数据存入redis
            //redisTemplate.opsForValue().set("dish_"+categoryId,dishDtos);
            return R.success(dishDtos);
        }
        return R.error("查询失败");

    }


}
